package eye_report

import (
	"context"
	"fmt"
	"github.com/chromedp/chromedp"
	"go_19/global"
	"go_19/models/zz"
	"go_19/utils"
	"os"
	"time"
)

type YandiAi interface {
	InitDownload()
	getAllYandiReocrd() []zz.YandiAiRecord
	DownloadWebPage(yandi zz.YandiAiRecord)
	//WebToPng(url sring)
}

type Yandi struct{}

func (c *Yandi) InitDownload() {
	//fmt.Println("ddd")
	list := c.GetYandiAiRecord()
	fmt.Println(len(list))
	for _, v := range list {
		//v.AiURL.String = "http://saas-project.224.com/health"
		//v.AiURL.String = "https://www.baidu.com"
		c.DownLoadAiReport(v)

	}
}

/**
 */
func (c *Yandi) DownLoadAiReport(yandi zz.YandiAiRecord) {
	dir := fmt.Sprintf("/Users/ctz/mnt/yandi_ai_report/%d/%s", yandi.DeptID, yandi.CreatedAt.Format("20060102"))
	if err := utils.CreateDirAll(dir, 0755); err == nil {
		filePath := fmt.Sprintf(dir+"/%d.png", yandi.ID)
		fmt.Println(filePath)
		if exist := utils.FileExist(filePath); !exist {
			fmt.Println(yandi.ID, yandi.AiURL)
			if err, bytes := cutPic(yandi.AiURL.String); err != nil {
				global.GVA_LOG.Error(err)
			} else {
				fmt.Println("--", len(bytes), "--")
				fileSize := len(bytes)
				if fileSize < 10 {
					panic("图片截图失败")
				}
				if err := os.WriteFile(filePath, bytes, 0755); err != nil {
					global.GVA_LOG.Error(err)
				} else {

				}
			}
		} else {
			info, _ := os.Stat(filePath)
			fmt.Println(info.Size())
		}
	}

	/*err, bytes := chromedp.WebToPng(yandi.RequestAi)
	if err == nil {
		if err := os.WriteFile("baidu_PC.png", bytes, 0755); err != nil {
			log.Fatal(err)
		} else {

		}
	}*/

}

func (c *Yandi) GetYandiAiRecord() []zz.YandiAiRecord {
	var records []zz.YandiAiRecord
	q := global.GVA_DB.Model(zz.YandiAiRecord{}).Where("is_deleted=?", 0)
	q.Where(q.Where("ai_url!=?", "").Where("ai_url is not null"))
	//q.Where("id=?", 111921)
	//q.Where("id=?", 66)
	q.Limit(100)
	q.Scan(&records)
	return records
}

func cutPic(targetUrl string) (error, []byte) {
	ctx, cancel := chromedp.NewContext(context.Background())
	defer cancel()

	var b2 []byte
	if err := chromedp.Run(ctx, newTask(targetUrl, &b2)); err != nil {
		return err, nil
	}
	return nil, b2
}

func newTask(targetUrl string, res *[]byte) chromedp.Tasks {
	return chromedp.Tasks{
		chromedp.EmulateViewport(1920, 2000),
		chromedp.Navigate(targetUrl),
		chromedp.WaitReady("body"),
		chromedp.Sleep(1 * time.Second),
		chromedp.FullScreenshot(res, 100),
		//chromedp.Screenshot("body", res, chromedp.NodeVisible),
		//chromedp.Navigate(targetUrl), // 导航到网页
		//chromedp.Screenshot(file, &chromedp.ScreenshotOptions{
		//	FullPage: true, // 捕获整个网页
		//}),
	}
}
